import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getTemplateList, createTemplate, updateTemplate, deleteTemplate, getTemplateById, uploadVideoFile } from '@/services/project';
import { Table, Button, Form, Input, message, Popconfirm, Tag, Row, Col, ConfigProvider, Divider, Space, Typography, Card, Empty, Avatar, Switch, Modal, InputNumber } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined, DownloadOutlined, ReloadOutlined, DollarOutlined } from '@ant-design/icons';
import { motion } from 'framer-motion';
import TemplateList from '@/components/create-project/TemplateList';
import { ColumnGroupType, ColumnsType } from 'antd/es/table';
import ProjectFormModal from '@/components/project/ProjectFormModal';

// 定义项目管理页面使用的简单草稿类型
interface Draft {
    id: string;
    name: string;
    width: number;
    height: number;
    fps: number;
    creator: string;
    type: string;
    status: string;
    isPublic: boolean;
    detail: string;
    points_cost: number;
}

// 项目管理页面
const ProjectManager: React.FC = () => {
    const { Title, Text } = Typography;
    const { success, error } = message;
    const [form] = Form.useForm();
    const navigate = useNavigate();

    // 本地状态存储草稿列表
    const [drafts, setDrafts] = useState<Draft[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [editing, setEditing] = useState<Draft | null>(null);
    const [filterName, setFilterName] = useState<string>('');
    const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set());
    const [submitting, setSubmitting] = useState(false);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const [sortField, setSortField] = useState<string | null>(null);
    const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>(null);
    const [refreshing, setRefreshing] = useState(false);
    const [pricingModalVisible, setPricingModalVisible] = useState(false);
    const [pricingDraft, setPricingDraft] = useState<Draft | null>(null);
    const [pointsCost, setPointsCost] = useState<number>(0);
    const [saveModalVisible, setSaveModalVisible] = useState(false);
    const [materialPath, setMaterialPath] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [currentDraftId, setCurrentDraftId] = useState<string | null>(null);
    const [previewVideoFile, setPreviewVideoFile] = useState<File | null>(null);
    const [uploadingPreview, setUploadingPreview] = useState(false);
    const [currentPreviewVideoUrl, setCurrentPreviewVideoUrl] = useState<string>('');

    const handleCancel = () => {
        setModalVisible(false);
        setEditing(null);
        form.resetFields();
        setPreviewVideoFile(null);
        setCurrentPreviewVideoUrl('');
    };

    // 暗色主题样式配置
    const darkThemeStyles = {
        card: {
            backgroundColor: '#1f1f1f',
            borderColor: '#303030',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.3)',
        },
        table: {
            backgroundColor: '#1f1f1f',
            headerBg: '#141414',
            rowHoverBg: '#303030',
        },
        text: {
            primary: '#ffffff',
            secondary: '#b3b3b3',
        },
    };

    // 页面加载时获取草稿列表
    useEffect(() => {
        fetchDrafts();
    }, []);

    // 获取草稿列表并存储到本地状态
    const fetchDrafts = async () => {
        try {
            const result = (await getTemplateList()).data;
            // 后端返回的数据结构是 { drafts: Draft[] }
            if (!result.drafts || !Array.isArray(result.drafts)) {
                setDrafts([]);
                return;
            }
            setDrafts(result.drafts);
        } catch (error) {
            console.error('获取草稿列表失败:', error);
            message.error('获取草稿列表失败，请稍后重试');
        }
    };

    // 刷新草稿列表
    const handleRefresh = async () => {
        try {
            setRefreshing(true);
            fetchDrafts();
            message.success('刷新成功');
        } catch (error) {
            message.error('刷新失败，请稍后重试');
        } finally {
            setRefreshing(false);
        }
    };

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            setSubmitting(true);

            // 构建发送给后端的数据结构
            let templateData = {
                ...values,
                status: '未编辑', // 固定设置为未编辑状态
            };

            // 如果选择了预览视频，先上传视频
            if (previewVideoFile) {
                setUploadingPreview(true);
                try {
                    const uploadFormData = new FormData();
                    uploadFormData.append('file', previewVideoFile);
                    const uploadResponse = await uploadVideoFile(uploadFormData);
                    // 根据实际响应结构获取文件URL
                    templateData.preview_video_url = uploadResponse.data.file_url || uploadResponse.data.url || uploadResponse.data.path;
                } catch (uploadError) {
                    console.error('上传预览视频失败:', uploadError);
                    message.error('上传预览视频失败，请重试');
                    return;
                } finally {
                    setUploadingPreview(false);
                }
            } else if (editing && currentPreviewVideoUrl) {
                // 如果是编辑模式且没有选择新视频，保持原有预览视频URL
                templateData.preview_video_url = currentPreviewVideoUrl;
            }

            if (editing) {
                // 调用后端API更新草稿，传入草稿ID
                await updateTemplate(editing.id, templateData);
                success('修改成功');
            } else {
                // 调用后端API创建模板
                await createTemplate(templateData);
                success('草稿创建成功');
            }
            // 重新获取草稿列表以更新界面
            await fetchDrafts();
            setModalVisible(false);
            setEditing(null);
            setPreviewVideoFile(null);
            setCurrentPreviewVideoUrl('');
        } catch (e) {
            if (e && (e as any).errorFields) {
                error('表单验证失败，请检查必填字段是否填写');
            } else {
                console.error('操作草稿失败:', e);
                error('操作失败，请查看控制台日志或联系管理员');
            }
        } finally {
            setSubmitting(false);
        }
    };

    const handleDelete = async (id: string) => {
        try {
            // 添加到删除中的ID集合
            setDeletingIds((prev) => new Set(prev).add(id));
            await deleteTemplate(id);
            success('删除成功');
            // 删除成功后重新获取草稿列表以更新界面
            await fetchDrafts();
        } catch (err) {
            console.error('Failed to delete draft:', err);
            error('删除失败，请重试');
        } finally {
            // 从删除中的ID集合移除
            setDeletingIds((prev) => {
                const newSet = new Set(prev);
                newSet.delete(id);
                return newSet;
            });
        }
    };

    const handleDraftClick = async (record: Draft) => {
        navigate(`/editor?draftId=${record.id}`);
    };

    const openEdit = async (record: Draft) => {
        // 设置编辑状态并显示模态框
        setEditing(record);
        setModalVisible(true);

        try {
            // 调用接口获取草稿详情
            const response = await getTemplateById(record.id);
            // 卫语句：检查API响应是否有效
            if (!response.data) {
                console.warn('获取草稿详情失败，使用列表数据');
                form.setFieldsValue(record);
                return;
            }
            // API响应有效，提取表单需要的数据
            const details = response.data.draft_info;
            const formData = {
                name: details.name || '',
                width: details.width || 1920,
                height: details.height || 1080,
                fps: details.fps || 30,
                creator: details.creator || '',
                type: details.type || '视频编辑',
                isPublic: details.isPublic || false,
                detail: details.detail || '',
            };

            // 设置当前预览视频URL
            setCurrentPreviewVideoUrl(details.preview_video_url || '');

            // 设置表单数据
            form.setFieldsValue(formData);
        } catch (error) {
            console.error('获取草稿详情失败:', error);
            message.error('获取草稿详情失败，请稍后重试');
            // 使用传入的record数据作为备选
            form.setFieldsValue(record);
        }
    };

    const openAdd = () => {
        setEditing(null);
        setModalVisible(true);
        form.resetFields();
        setPreviewVideoFile(null);
        setCurrentPreviewVideoUrl('');
    };

    // 处理预览视频文件选择
    const handlePreviewVideoSelect = (file: File) => {
        setPreviewVideoFile(file);
        return false; // 阻止自动上传
    };

    // 移除预览视频文件
    const handlePreviewVideoRemove = () => {
        setPreviewVideoFile(null);
        setCurrentPreviewVideoUrl('');
    };

    // 打开定价模态框
    const openPricing = (record: Draft) => {
        setPricingDraft(record);
        setPointsCost(record.points_cost || 0);
        setPricingModalVisible(true);
    };

    // 关闭定价模态框
    const closePricing = () => {
        setPricingModalVisible(false);
        setPricingDraft(null);
        setPointsCost(0);
    };

    // 保存定价
    const handlePricingSave = async () => {
        if (!pricingDraft) return;

        try {
            const templateData = {
                points_cost: pointsCost,
            };
            await updateTemplate(pricingDraft.id, templateData);
            success('定价更新成功');
            await fetchDrafts();
            closePricing();
        } catch (error) {
            console.error('更新定价失败:', error);
            message.error('更新定价失败，请重试');
        }
    };

    // 打开保存模态框
    const openSaveModal = (draftId: string) => {
        setCurrentDraftId(draftId);
        setSaveModalVisible(true);
        setMaterialPath('');
    };

    // 关闭保存模态框
    const closeSaveModal = () => {
        setSaveModalVisible(false);
        setCurrentDraftId(null);
        setMaterialPath('');
    };

    // 处理保存确认
    const handleSaveConfirm = async () => {
        if (!materialPath.trim()) {
            message.warning('请输入素材路径');
            return;
        }

        if (!currentDraftId) {
            message.error('未找到草稿ID');
            return;
        }

        setIsSubmitting(true);
        try {
            // 使用新的API，将素材路径作为查询参数发送并下载文件
            await downloadDraftWithMaterialPath(materialPath, currentDraftId);

            message.success('草稿压缩包下载成功');
            closeSaveModal();
        } catch (error) {
            console.error('下载失败:', error);
            message.error(error instanceof Error ? error.message : '下载失败，请重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    // 发送素材路径到后端并下载草稿文件
    const downloadDraftWithMaterialPath = async (path: string, draftId: string) => {
        // 根据后端API示例，将material_path作为查询参数
        const url = `/api/draft/script-file/${draftId}/?material_path=${encodeURIComponent(path)}`;

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${localStorage.getItem('auth_token') || ''}`,
                'Content-Type': 'application/json',
            },
        });

        if (!response.ok) {
            throw new Error('下载草稿文件失败');
        }

        // 处理zip文件下载
        const blob = await response.blob();
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `draft-${draftId}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    };

    // 处理排序
    const handleTableChange = (_pagination: any, _filters: any, sorter: any) => {
        if (sorter.field) {
            setSortField(sorter.field);
            setSortOrder(sorter.order);
        }
    };

    const columns: ColumnsType<Draft> | ColumnGroupType<Draft> = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            sorter: true,
            render: (text: string) => (
                <Text
                    strong
                    style={{
                        fontSize: '14px',
                        color: darkThemeStyles.text.primary,
                    }}
                >
                    {text}
                </Text>
            ),
        },
        {
            title: '创建人',
            dataIndex: 'creator',
            key: 'creator',
            sorter: true,
            render: (text: string) => (
                <div
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px',
                    }}
                >
                    <Avatar
                        size="small"
                        style={{
                            backgroundColor: `hsl(${text.charCodeAt(0) * 10}, 70%, 60%)`,
                            color: '#fff',
                            border: '1px solid rgba(255, 255, 255, 0.15)',
                        }}
                    >
                        {text.charAt(0).toUpperCase()}
                    </Avatar>
                    <Text style={{ color: darkThemeStyles.text.primary }}>{text}</Text>
                </div>
            ),
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            sorter: true,
            render: (text: string) => (
                <Tag color={text === '视频编辑' ? 'blue' : 'green'} style={{ border: '1px solid rgba(255, 255, 255, 0.15)' }}>
                    {text}
                </Tag>
            ),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            sorter: true,
            render: (v: string) => (
                <Tag color={v === '正在编辑' ? 'processing' : v === '未编辑' ? 'default' : v === '已完成' ? 'success' : 'warning'} style={{ border: '1px solid rgba(255, 255, 255, 0.15)' }}>
                    {v}
                </Tag>
            ),
        },
        {
            title: '是否公开',
            dataIndex: 'isPublic',
            key: 'isPublic',
            sorter: true,
            render: (v: boolean, record: Draft) => (
                <Switch
                    checked={v}
                    onChange={async (checked, event) => {
                        event.stopPropagation();
                        try {
                            // 创建要更新的数据对象，只包含需要更新的字段
                            const templateData = {
                                isPublic: checked,
                            };
                            // 调用后端API更新草稿
                            await updateTemplate(record.id, templateData);
                            success('更新成功');
                            // 重新获取草稿列表以更新界面
                            await fetchDrafts();
                        } catch (error) {
                            console.error('更新草稿失败:', error);
                            message.error('更新失败，请重试');
                        }
                    }}
                />
            ),
        },
        {
            title: '模板价格',
            dataIndex: 'points_cost',
            key: 'points_cost',
            sorter: true,
            render: (value: number) => <Text style={{ color: darkThemeStyles.text.primary }}>{value || 0} 积分</Text>,
        },
        {
            title: '描述',
            dataIndex: 'detail',
            key: 'detail',
            ellipsis: {
                showTitle: true,
            },
            render: (text: string) => <Text style={{ color: darkThemeStyles.text.secondary }}>{text || '无描述'}</Text>,
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 220,
            render: (_: any, record: Draft) => (
                <Space size="small">
                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Button
                            type="link"
                            icon={<EditOutlined style={{ color: '#1890ff' }} />}
                            size="small"
                            onClick={(e) => {
                                e.stopPropagation();
                                openEdit(record);
                            }}
                            title="编辑"
                            style={{ color: '#1890ff' }}
                        />
                    </motion.div>
                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Button
                            type="link"
                            icon={<DollarOutlined style={{ color: '#52c41a' }} />}
                            size="small"
                            onClick={(e) => {
                                e.stopPropagation();
                                openPricing(record);
                            }}
                            title="定价"
                            style={{ color: '#52c41a' }}
                        />
                    </motion.div>
                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Button
                            type="link"
                            icon={<DownloadOutlined style={{ color: '#1890ff' }} />}
                            size="small"
                            onClick={(e) => {
                                e.stopPropagation();
                                openSaveModal(record.id);
                            }}
                            title="保存草稿"
                            style={{ color: '#1890ff' }}
                        />
                    </motion.div>
                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                        <Popconfirm
                            title="确定删除？"
                            description="此操作不可撤销，删除后草稿将无法恢复。"
                            onConfirm={(e?: React.MouseEvent) => {
                                e?.stopPropagation();
                                handleDelete(record.id);
                            }}
                            onCancel={(e?: React.MouseEvent) => {
                                e?.stopPropagation();
                            }}
                            okText="确认"
                            cancelText="取消"
                        >
                            <Button type="link" danger icon={<DeleteOutlined />} size="small" loading={deletingIds.has(record.id)} onClick={(e) => e.stopPropagation()} title="删除" />
                        </Popconfirm>
                    </motion.div>
                </Space>
            ),
        },
    ];

    // 筛选和排序数据
    const filteredData = [...drafts]
        .filter((item) => item.name.toLowerCase().includes(filterName.trim().toLowerCase()))
        .sort((a, b) => {
            if (!sortField) return 0;
            if (a[sortField as keyof Draft] < b[sortField as keyof Draft]) {
                return sortOrder === 'ascend' ? -1 : 1;
            }
            if (a[sortField as keyof Draft] > b[sortField as keyof Draft]) {
                return sortOrder === 'ascend' ? 1 : -1;
            }
            return 0;
        });

    return (
        <div
            style={{
                maxWidth: '1200px',
                margin: '0 auto',
                padding: '0 20px',
            }}
        >
            <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col>
                    <Input
                        placeholder="筛选模板名称"
                        value={filterName}
                        onChange={(e) => setFilterName(e.target.value)}
                        allowClear
                        style={{
                            width: 200,
                            backgroundColor: '#2a2a2a',
                            borderColor: '#434343',
                            color: darkThemeStyles.text.primary,
                            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                            borderRadius: '4px',
                        }}
                        prefix={
                            <SearchOutlined
                                style={{
                                    color: darkThemeStyles.text.secondary,
                                }}
                            />
                        }
                    />
                </Col>
                <Col>
                    <Button
                        type="primary"
                        onClick={openAdd}
                        style={{
                            background: '#177ddc',
                            borderColor: '#177ddc',
                            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                        }}
                    >
                        新增模板
                    </Button>
                </Col>
            </Row>
            <Card
                title={
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                        }}
                    >
                        <Title
                            level={4}
                            style={{
                                margin: 0,
                                color: darkThemeStyles.text.primary,
                            }}
                        >
                            我的草稿列表
                        </Title>
                        <div
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '12px',
                                color: darkThemeStyles.text.secondary,
                            }}
                        >
                            <Text
                                type="secondary"
                                style={{
                                    color: darkThemeStyles.text.secondary,
                                }}
                            >
                                共 {drafts.length} 个草稿
                            </Text>
                            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                                <Button
                                    type="text"
                                    icon={<ReloadOutlined />}
                                    loading={refreshing}
                                    onClick={handleRefresh}
                                    title="刷新草稿列表"
                                    style={{
                                        border: '1px solid rgba(255, 255, 255, 0.15)',
                                        borderRadius: '4px',
                                    }}
                                >
                                    刷新
                                </Button>
                            </motion.div>
                        </div>
                    </div>
                }
                className="table-card"
                style={{
                    backgroundColor: darkThemeStyles.card.backgroundColor,
                    borderColor: darkThemeStyles.card.borderColor,
                    boxShadow: darkThemeStyles.card.boxShadow,
                }}
            >
                <ConfigProvider
                    theme={{
                        components: {
                            Table: {
                                colorBgContainer: darkThemeStyles.table.backgroundColor,
                                borderColor: darkThemeStyles.card.borderColor,
                                headerBg: darkThemeStyles.table.headerBg,
                                headerColor: darkThemeStyles.text.primary,
                                rowHoverBg: darkThemeStyles.table.rowHoverBg,
                                fontSize: 14,
                                colorText: darkThemeStyles.text.primary,
                                colorTextSecondary: darkThemeStyles.text.secondary,
                            },
                            Pagination: {
                                colorText: darkThemeStyles.text.primary,
                                colorTextDisabled: 'rgba(255, 255, 255, 0.25)',
                                colorBgContainer: darkThemeStyles.card.backgroundColor,
                            },
                        },
                    }}
                >
                    {filteredData.length === 0 ? (
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={filterName ? '没有找到匹配的草稿' : '暂无草稿数据'} className="empty-dark-status" />
                    ) : (
                        <Table
                            rowKey="id"
                            columns={columns}
                            dataSource={filteredData}
                            pagination={{
                                current: currentPage,
                                pageSize: pageSize,
                                total: filteredData.length,
                                showSizeChanger: true,
                                showQuickJumper: true,
                                showTotal: (total) => `共 ${total} 条`,
                                pageSizeOptions: ['5', '10', '20', '50'],
                                onChange: (page, size) => {
                                    setCurrentPage(page);
                                    setPageSize(size);
                                },
                                size: 'small',
                            }}
                            bordered
                            scroll={{ x: 'max-content' }}
                            onChange={handleTableChange}
                            onRow={(record) => ({
                                onClick: () => handleDraftClick(record),
                                style: {
                                    cursor: 'pointer',
                                    transition: 'all 0.2s ease',
                                },
                                onMouseEnter: (e) => {
                                    e.currentTarget.style.backgroundColor = '#f5f5f5';
                                    e.currentTarget.style.transform = 'translateY(-1px)';
                                },
                                onMouseLeave: (e) => {
                                    e.currentTarget.style.backgroundColor = '';
                                    e.currentTarget.style.transform = '';
                                },
                            })}
                            components={{
                                body: (props: any) => <motion.tbody {...props} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }} />,
                            }}
                        />
                    )}
                </ConfigProvider>
            </Card>
            <Divider style={{ margin: '12px 0' }} />
            {/* 公开草稿模板 */}
            <TemplateList />
            <ProjectFormModal
                visible={modalVisible}
                submitting={submitting || uploadingPreview}
                editing={editing}
                form={form}
                onOk={handleOk}
                onCancel={handleCancel}
                previewVideoFile={previewVideoFile}
                onPreviewVideoSelect={handlePreviewVideoSelect}
                onPreviewVideoRemove={handlePreviewVideoRemove}
                currentPreviewVideoUrl={currentPreviewVideoUrl}
            />

            {/* 保存草稿模态框 */}
            <ConfigProvider
                theme={{
                    components: {
                        Modal: {
                            contentBg: darkThemeStyles.card.backgroundColor,
                            headerBg: darkThemeStyles.card.backgroundColor,
                            titleColor: darkThemeStyles.text.primary,
                            colorText: darkThemeStyles.text.primary,
                        },
                        Input: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: darkThemeStyles.text.primary,
                            colorTextPlaceholder: darkThemeStyles.text.secondary,
                            colorPrimary: '#177ddc',
                            colorPrimaryHover: '#4096ff',
                        },
                        Button: {
                            colorPrimary: '#177ddc',
                            colorPrimaryHover: '#4096ff',
                            colorText: darkThemeStyles.text.primary,
                        },
                    },
                }}
            >
                <Modal
                    title="设置素材路径"
                    open={saveModalVisible}
                    onOk={handleSaveConfirm}
                    onCancel={closeSaveModal}
                    confirmLoading={isSubmitting}
                    okText="确认保存"
                    cancelText="取消"
                    width={500}
                    style={{
                        backgroundColor: darkThemeStyles.card.backgroundColor,
                    }}
                    bodyStyle={{
                        backgroundColor: darkThemeStyles.card.backgroundColor,
                        padding: '24px',
                    }}
                >
                    <div style={{ padding: '0' }}>
                        <p style={{ marginBottom: '16px', color: darkThemeStyles.text.secondary }}>请输入本地素材文件夹路径，系统将使用此路径处理素材文件：</p>
                        <Input placeholder="例如：C:\Users\用户名\Desktop\素材文件夹" value={materialPath} onChange={(e) => setMaterialPath(e.target.value)} size="large" disabled={isSubmitting} />
                        <p style={{ marginTop: '8px', fontSize: '12px', color: darkThemeStyles.text.secondary }}>请确保路径存在且包含项目所需的素材文件，系统将生成包含草稿和素材的zip压缩包</p>
                    </div>
                </Modal>
            </ConfigProvider>

            {/* 定价模态框 */}
            <ConfigProvider
                theme={{
                    components: {
                        Modal: {
                            contentBg: darkThemeStyles.card.backgroundColor,
                            headerBg: darkThemeStyles.card.backgroundColor,
                            titleColor: darkThemeStyles.text.primary,
                            colorText: darkThemeStyles.text.primary,
                        },
                        InputNumber: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: darkThemeStyles.text.primary,
                            colorTextPlaceholder: darkThemeStyles.text.secondary,
                            colorPrimary: '#177ddc',
                            colorPrimaryHover: '#4096ff',
                        },
                        Button: {
                            colorPrimary: '#177ddc',
                            colorPrimaryHover: '#4096ff',
                            colorText: darkThemeStyles.text.primary,
                        },
                    },
                }}
            >
                <Modal
                    title="设置模板价格"
                    open={pricingModalVisible}
                    onOk={handlePricingSave}
                    onCancel={closePricing}
                    okText="保存"
                    cancelText="取消"
                    style={{
                        backgroundColor: darkThemeStyles.card.backgroundColor,
                    }}
                    bodyStyle={{
                        backgroundColor: darkThemeStyles.card.backgroundColor,
                        padding: '24px',
                    }}
                >
                    <div style={{ padding: '0' }}>
                        <div
                            style={{
                                padding: '16px',
                                backgroundColor: '#2a2a2a',
                                borderRadius: '8px',
                                border: `1px solid ${darkThemeStyles.card.borderColor}`,
                                marginBottom: '20px',
                            }}
                        >
                            <Text
                                style={{
                                    color: darkThemeStyles.text.secondary,
                                    fontSize: '12px',
                                    marginBottom: '4px',
                                    display: 'block',
                                }}
                            >
                                模板名称
                            </Text>
                            <Text
                                style={{
                                    color: darkThemeStyles.text.primary,
                                    fontSize: '16px',
                                    fontWeight: 500,
                                    display: 'block',
                                }}
                            >
                                {pricingDraft?.name}
                            </Text>
                        </div>

                        <div>
                            <Text
                                style={{
                                    color: darkThemeStyles.text.primary,
                                    marginBottom: '12px',
                                    display: 'block',
                                    fontSize: '14px',
                                    fontWeight: 500,
                                }}
                            >
                                积分价格
                            </Text>
                            <InputNumber
                                value={pointsCost}
                                onChange={(value) => setPointsCost(value || 0)}
                                min={0}
                                max={999999}
                                style={{
                                    width: '100%',
                                    height: '40px',
                                }}
                                placeholder="请输入积分价格"
                                addonAfter={<span style={{ color: darkThemeStyles.text.secondary }}>积分</span>}
                            />
                            <Text
                                style={{
                                    color: darkThemeStyles.text.secondary,
                                    fontSize: '12px',
                                    marginTop: '8px',
                                    display: 'block',
                                }}
                            >
                                设置用户购买此模板需要消耗的积分数量
                            </Text>
                        </div>
                    </div>
                </Modal>
            </ConfigProvider>
        </div>
    );
};

export default ProjectManager;
